package com.elock.intf.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.elock.base.core.Filter;
import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.Sequence;
import com.elock.base.core.service.impl.BaseServiceImpl;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.ExceptionUtil;
import com.elock.entity.CompanyInfo;
import com.elock.entity.Member;
import com.elock.entity.MemberSaleOrg;
import com.elock.entity.PcRole;
import com.elock.entity.PcUserRole;
import com.elock.entity.SaleOrg;
import com.elock.entity.Terminal;
import com.elock.entity.TerminalMember;
import com.elock.intf.dao.IntfMemberDao;
import com.elock.intf.dao.IntfSaleOrgDao;
import com.elock.intf.service.IntfMemberService;
import com.elock.service.CompanyInfoService;
import com.elock.service.MemberSaleOrgBaseService;
import com.elock.service.PcRoleBaseService;
import com.elock.service.PcUserRoleBaseService;
import com.elock.service.SaleOrgBaseService;
import com.elock.service.TerminalMemberService;
import com.elock.service.TerminalService;

/**
 * 用户
 * @author 仁德
 */
@Service("intfMemberServiceImpl")
public class IntfMemberServiceImpl extends BaseServiceImpl<Member>
		implements IntfMemberService {

	@Resource(name = "intfMemberDao")
	private IntfMemberDao intfMemberDao;
	@Resource(name = "saleOrgBaseServiceImpl")
	private SaleOrgBaseService saleOrgBaseService;
	@Resource(name = "pcUserRoleBaseServiceImpl")
	private PcUserRoleBaseService pcUserRoleBaseService;
	@Resource(name = "memberSaleOrgBaseServiceImpl")
	private MemberSaleOrgBaseService memberSaleOrgBaseService;
	@Resource(name = "pcRoleBaseServiceImpl")
	private PcRoleBaseService pcRoleBaseService;
	@Resource(name = "terminalMemberServiceImpl")
	private TerminalMemberService terminalMemberService;
	@Resource(name = "terminalServiceImpl")
	private TerminalService terminalService;
	@Resource(name = "companyInfoServiceImpl")
	private CompanyInfoService companyInfoService;
	@Resource(name = "intfSaleOrgDao")
	private IntfSaleOrgDao intfSaleOrgDao;

	@Override
	@Transactional(readOnly = true)
	public Member findByUsername(String username, String companycode) {
		return intfMemberDao.findByUsername(username, companycode);
	}

	@Override
	@Transactional(readOnly = true)
	public Member findByMobile(String mobile, String companycode) {
		return intfMemberDao.findByMobile(mobile, companycode);
	}

	@Override
	@Transactional
	public void updateb(String companycode, Member member, String saleOrgSn,
			String[] roleName) {

		if (ConvertUtil.isEmpty(companycode)) {
			ExceptionUtil.throwServiceException("请传入企业编号");
		}
		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("company_code", companycode));
		CompanyInfo companyInfo = companyInfoService.find(filters);
		if (companyInfo == null) {
			ExceptionUtil.throwServiceException("不存在企业编号为[" + companycode + "]的企业");
		}
		String username = member.getUsername();
		if (ConvertUtil.isEmpty(username)) {
			ExceptionUtil.throwServiceException("请传入用户名");
		}
		String mobile = member.getMobile();
		if (ConvertUtil.isEmpty(mobile)) {
			ExceptionUtil.throwServiceException("请传入手机号");
		}

		Member pMember = intfMemberDao.findByUsername(member.getUsername(), companycode);
		if (pMember == null) {

			member.setCompanyInfoId(companyInfo.getId());
			member.setIsLocked(false);
			member.setLoginFailureCount(0);
			member.setIsEnabled(true);
			member.setMemberType(0);
			member.setPassword(DigestUtils.md5Hex(member.getPassword()));
			if (member.getName() == null) {
				member.setName(member.getUsername());
			}
		}
		else {
			if (!ConvertUtil.isEmpty(member.getName())) {
				pMember.setName(member.getName());
			}
			if (!ConvertUtil.isEmpty(member.getMobile())) {
				pMember.setMobile(member.getMobile());
			}
			if (!ConvertUtil.isEmpty(member.getPassword())) {
				pMember.setPassword(DigestUtils.md5Hex(member.getPassword()));
			}
			update(pMember);
		}

		SaleOrg saleOrg = intfSaleOrgDao.findBySaleOrgSn(saleOrgSn);
		saveStoreMemberOfSaleOrg(saleOrg == null ? null : saleOrg.getId(), pMember);
	}

	@Override
	@Transactional
	public void updatet(String companycode, Member member, String saleOrgSn,
			String[] terminalNum) {

		if (ConvertUtil.isEmpty(companycode)) {
			ExceptionUtil.throwServiceException("请传入企业编号");
		}
		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("company_code", companycode));
		CompanyInfo companyInfo = companyInfoService.find(filters);
		if (companyInfo == null) {
			ExceptionUtil.throwServiceException("不存在企业编号为[" + companycode + "]的企业");
		}
		String pinCode = member.getPinCode();
		if (ConvertUtil.isEmpty(pinCode)) {
			ExceptionUtil.throwServiceException("请传入操作员PIN码");
		}

		Member pMember = intfMemberDao.findByPinCode(pinCode);
		if (pMember == null) {

			String sn = Sequence.getInstance().getSequence(null);
			member.setCompanyInfoId(companyInfo.getId());
			member.setUsername(sn);
			member.setMobile(sn);
			member.setIsLocked(false);
			member.setLoginFailureCount(0);
			member.setIsEnabled(true);
			member.setMemberType(1);
			member.setPassword(DigestUtils.md5Hex("888888"));
			if (member.getName() == null) {
				member.setName(member.getUsername());
			}
		}
		else {
			if (!ConvertUtil.isEmpty(member.getName())) {
				pMember.setName(member.getName());
			}
			if (!ConvertUtil.isEmpty(member.getPinCode())) {
				pMember.setPinCode(member.getPinCode());
			}
			if (!ConvertUtil.isEmpty(member.getOperatePassword())) {
				pMember.setOperatePassword(member.getOperatePassword());
			}
			update(pMember);
		}

		SaleOrg saleOrg = intfSaleOrgDao.findBySaleOrgSn(saleOrgSn);
		saveStoreMemberOfSaleOrg(saleOrg == null ? null : saleOrg.getId(), pMember);
	}

	/**
	 * 保存用户组织关联关系
	 */
	public void saveStoreMemberOfSaleOrg(Long saleOrgId, Member member) {

		SaleOrg saleOrg = saleOrgBaseService.find(saleOrgId);
		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("member", member));
		List<MemberSaleOrg> memberSaleOrgs = memberSaleOrgBaseService.findList(null,
				filters,
				null);
		MemberSaleOrg memberSaleOrg = null;
		for (MemberSaleOrg org : memberSaleOrgs) {
			if (saleOrg != null && org.getSaleOrg().equals(saleOrg)) {
				memberSaleOrg = org;
			}
			else {
				memberSaleOrgBaseService.delete(org);
			}
		}
		if (memberSaleOrg == null && saleOrg != null) {
			memberSaleOrg = new MemberSaleOrg();
			memberSaleOrg.setSaleOrg(saleOrg);
			memberSaleOrg.setMember(member);
			memberSaleOrgBaseService.save(memberSaleOrg);
		}
	}

	/**
	 * 保存用户角色
	 */
	public void saveUserRole(Long[] roleId, Member member, Boolean isAdministrator) {

		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("member", member));
		List<PcUserRole> nUserRoles = pcUserRoleBaseService.findList(null, filters, null);
		List<PcRole> oldRoles = new ArrayList<PcRole>();
		for (PcUserRole userRole : nUserRoles) {
			oldRoles.add(userRole.getPcRole());
		}
		List<PcRole> roles = new ArrayList<PcRole>();
		if (roleId != null && roleId.length > 0) {
			for (Long id : roleId) {
				PcRole pcRole = pcRoleBaseService.find(id);
				roles.add(pcRole);
			}
		}

		for (PcRole role : roles) {
			if (!oldRoles.contains(role)) {
				PcUserRole pcUserRole = new PcUserRole();
				pcUserRole.setMember(member);
				pcUserRole.setPcRole(role);
				pcUserRoleBaseService.save(pcUserRole);
			}
		}
		for (PcUserRole userRole : nUserRoles) {
			if (!roles.contains(userRole.getPcRole())
					&& userRole.getPcRole().getCompanyInfoId() != null) {
				pcUserRoleBaseService.delete(userRole);
			}
		}
	}

	/**
	 * 保存终端设备用户关联
	 */
	public void saveTerminalMember(Long[] terminalId, Member member) {

		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("memberId", member.getId()));
		List<TerminalMember> terminalMembers = terminalMemberService.findList(null,
				filters,
				null);
		List<Long> oTerminalIds = new ArrayList<Long>();
		for (TerminalMember terminalMember : terminalMembers) {
			oTerminalIds.add(terminalMember.getTerminalId());
		}

		List<Long> nTerminalIds = new ArrayList<Long>();
		if (terminalId != null && terminalId.length > 0) {
			for (Long nTerminalId : terminalId) {
				nTerminalIds.add(nTerminalId);
			}
		}

		for (Long nTerminalId : nTerminalIds) {
			if (!oTerminalIds.contains(nTerminalId)) {
				TerminalMember tMember = new TerminalMember();
				tMember.setTerminalId(nTerminalId);
				Terminal terminal = terminalService.find(nTerminalId);
				tMember.setTerminalNum(terminal.getTerminalNum());
				tMember.setMemberId(member.getId());
				tMember.setUsername(member.getUsername());
				terminalMemberService.save(tMember);
			}
		}

		for (TerminalMember tMember : terminalMembers) {
			if (!nTerminalIds.contains(tMember.getTerminalId())) {
				terminalMemberService.delete(tMember);
			}
		}
	}

	@Override
	public Page<Map<String, Object>> findPage(String username, String mobile, String name,
			String pinCode, Long saleOrgId, String startTime, String endTime,
			Integer memberType, Pageable pageable) {
		return intfMemberDao.findPage(username,
				mobile,
				name,
				pinCode,
				saleOrgId,
				startTime,
				endTime,
				memberType,
				pageable);
	}

	@Override
	@Transactional
	public void deleteMember(String companycode, String username, String pinCode,
			int memberType) {

		if (ConvertUtil.isEmpty(companycode)) {
			ExceptionUtil.throwServiceException("请传入企业编号");
		}
		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("company_code", companycode));
		CompanyInfo companyInfo = companyInfoService.find(filters);
		if (companyInfo == null) {
			ExceptionUtil.throwServiceException("不存在企业编号为[" + companycode + "]的企业");
		}
		Member member = null;
		if (memberType == 0) {
			if (ConvertUtil.isEmpty(username)) {
				ExceptionUtil.throwServiceException("请传入用户名");
			}
			member = intfMemberDao.findByUsername(username, companycode);
			if (member == null) {
				ExceptionUtil.throwServiceException("该企业不存在用户名为[" + username + "]的用户");
			}
		}
		else {
			if (ConvertUtil.isEmpty(pinCode)) {
				ExceptionUtil.throwServiceException("请传入操作员PIN码");
			}
			member = intfMemberDao.findByPinCode(pinCode);
			if (member == null) {
				ExceptionUtil
						.throwServiceException("该企业不存在操作员PIN码为[" + username + "]的用户");
			}
		}
		filters.clear();
		filters.add(Filter.eq("member", member));
		List<PcUserRole> userRoles = pcUserRoleBaseService.findList(null, filters, null);
		for (PcUserRole userRole : userRoles) {
			pcUserRoleBaseService.delete(userRole);
		}
		if (memberSaleOrgBaseService.exists(Filter.eq("member", member))) {
			MemberSaleOrg memberSaleOrg = memberSaleOrgBaseService.find(filters);
			memberSaleOrgBaseService.delete(memberSaleOrg);
		}
		if (terminalMemberService.exists(Filter.eq("memberId", member.getId()))) {
			filters.clear();
			filters.add(Filter.eq("memberId", member.getId()));
			List<TerminalMember> terminalMembers = terminalMemberService.findList(null,
					filters,
					null);
			for (TerminalMember terminalMember : terminalMembers) {
				terminalMemberService.delete(terminalMember);
			}
		}
		delete(member);
	}

	@Override
	@Transactional(readOnly = true)
	public Member findByPinCode(String pinCode) {
		return intfMemberDao.findByPinCode(pinCode);
	}
}
